<?php

require_once("core.php");

/**
 * @param array $args : String mail, String psw
 * @return array json
*/
function login($args) {
	// Verification de l'existance des paramètres.
	if(!isset($args['mail']) || !isset($args['psw'])) {
		return array("back" => 2);
	}
	if(empty($args['mail']) || empty($args['psw'])) {
		return array("back" => 3);
	}

	$return = array("back" => 1);

	mysql_init();
	$req = "SELECT `uti_id`, `uti_email`, `uti_nom`, `uti_prenom`, `uti_naissance`, `uti_ville` FROM `utilisateur` WHERE `uti_email` = '" . $args['mail'] . "' AND `uti_motDePasse` = '" . $args['psw'] . "';";
	
	//$return["req"] = $req;
	
	$res = mysql_query($req);
	if($row = mysql_fetch_assoc($res)) {
		$return["back"] = 0;
		$return = $return + $row;
	}
	mysql_close();

	return $return;
}

function createUser($args) {
	$return = array("back" => 1);

	$req = "INSERT INTO `utilisateur` (`uti_id`, `uti_email`, `uti_motDePasse`, `uti_nom`, `uti_prenom`, `uti_naissance`, `uti_ville`, `spr_id`) ";
	$req .= "VALUES (NULL, ";
	$req .= "'" . $args['uti_email'] . "', '";
	$req .= $args['uti_motDePasse'] . "', '";
	$req .= $args['uti_nom'] . "', '";
	$req .= $args['uti_prenom'] . "', '";
	$req .= $args['uti_naissance'] . "', '";
	$req .= $args['uti_ville'] . "', ";
	$req .= "'0');";

	mysql_init();
	$res = mysql_query($req);
	if($res) {
		$return["back"] = 0;
	}
	mysql_close();

	return $return;
}

function loadSportList()
{
	$return = array(
			"back" => 1,
			"list" => array()
	);
	$succes = false;

	mysql_init();
	$req = "SELECT * FROM `sport` ORDER BY `spr_libelle`;";
	$res = mysql_query($req);
	if($res) {
		$return["back"] = 0;
		while($row = mysql_fetch_assoc($res)) {
			if (!$succes) {
				$succes = true;
			}
			array_push($return["list"], $row);
		}
	}
	mysql_close();

	return $return;
}

function loadEventList($args)
{
	$cond = " WHERE";
	$showPrivate = false;
	$compReqUser = "";
	$compReqEvent = "";
	if(isset($args['userId'])) {
		if($args['userId'] <> 0) {
			$showPrivate = true;
			$compReqUser = " JOIN `participant` AS `user` ON `evenement`.`evt_id` = `user`.`evt_id` AND `user`.`uti_id` = " . $args['userId'];
			$compReqEvent .= $cond . " `evenement`.`evt_debut` > NOW() - INTERVAL 1 DAY";
			$cond = " AND";
		}
	}
	if(isset($args['sportId'])) {
		if($args['sportId'] <> 0) {
			$compReqEvent = $cond . " `evenement`.`spr_id` = " . $args['sportId'];
			$cond = " AND";
			$compReqEvent .= $cond . " `evenement`.`evt_debut` > NOW()";
		}
	}
	if(isset($args['eventId'])) {
		if($args['eventId'] <> 0) {
			$showPrivate = true;
			$compReqEvent = $cond . " `evenement`.`spr_id` = " . $args['eventId'];
		}
	}
	if(!$showPrivate) {
		$compReqEvent .= $cond . " `evenement`.`evt_prive` != 1";
	}

	$return = array(
			"back" => 1,
			"list" => array()
	);

	mysql_init();
	$req  = "SELECT `evenement`.`evt_id` ,  `evt_debut` ,  `evt_fin` ,  `evt_latitude` ,  `evt_longitude` ,  `evt_nombreParticipant` ,  `sport`.`spr_id` ,  `spr_libelle`, `owner`.`uti_id`, `evt_prive`, `commentaire`.`com_contenu`, COALESCE(`invite`.`prt_acc`,-1) as `invite` FROM  `evenement`";
	$req .=	" JOIN `sport` ON  `sport`.`spr_id` =  `evenement`.`spr_id`";
	$req .=	" JOIN `commentaire` ON  `commentaire`.`evt_id` =  `evenement`.`evt_id` AND `commentaire`.`com_id` = 0";
	$req .= " JOIN `participant` AS `owner` ON `evenement`.`evt_id` = `owner`.`evt_id` AND `owner`.`prt_createur` = 1";
	$req .= " LEFT OUTER JOIN `participant` AS `invite` ON `evenement`.`evt_id` = `invite`.`evt_id` AND `invite`.`uti_id` = " . $args['curentUser'];
	$req .= $compReqUser . $compReqEvent;
	$req .=	" ORDER BY `evt_debut` LIMIT 20;";
	//echo $req;
	$res = mysql_query($req);
	if($res) {
		$return["back"] = 0;
		while($row = mysql_fetch_assoc($res)) {
			array_push($return["list"], $row);
		}
	}
	mysql_close();

	return $return;
}

function loadUserList($args) {
	// Verification de l'existance des paramètres.
	if(!isset($args['eventId'])) {
		if($args['eventId'] <> 0) {
			return array("back" => 2);
		}
	}

	$return = array(
			"back" => 1,
			"list" => array()
	);

	mysql_init();
	$req  = "SELECT `utilisateur`.`uti_id`, `uti_email`, `uti_nom`, `uti_prenom`, `uti_naissance`, `uti_ville`, `participant`.`prt_createur`, `participant`.`prt_acc` FROM `utilisateur`";
	$req .=	" JOIN `participant` ON `utilisateur`.`uti_id` = `participant`.`uti_id` AND `participant`.`evt_id` = " . $args['eventId'];
	$req .=	" JOIN `participant` as `createur` ON `createur`.`prt_createur` = 1 AND `createur`.`evt_id` = " . $args['eventId'];
	$req .=	" WHERE `participant`.`prt_acc` = 1 OR `createur`.`uti_id` = " . $args['userId'];
	$req .= " ORDER BY `prt_createur` DESC, `participant`.`prt_acc` DESC, `uti_prenom` ASC, `uti_nom` ASC;";
	
	$res = mysql_query($req);
	if($res) {
		$return["back"] = 0;
		while($row = mysql_fetch_assoc($res)) {
			array_push($return["list"], $row);
		}
	}
	mysql_close();

	return $return;
}

function subscription($args) {
	if(!isset($args['eventId']) || !isset($args['userId'])) {
		return array("back" => 2);
	}
	if(empty($args['eventId']) || empty($args['userId'])) {
		return array("back" => 3);
	}
	$return = array("back" => 1);

	$count = 0;

	mysql_init();
	$req = "SELECT COUNT(*) FROM `participant` WHERE `evt_id` = '" . $args['eventId'] . "' AND `uti_id` = '" . $args['userId'] . "';";
	$res = mysql_query($req);
	if($res) {
		if($row = mysql_fetch_row($res)) {
			$count = $row[0];
	
			if($count == 0) {
				$req = "INSERT INTO `participant` (`evt_id`, `uti_id`, `prt_createur`) VALUES ('" . $args['eventId'] . "', '" . $args['userId'] . "', b'0');";
				$res = mysql_query($req);
				if($res) {
					$return["back"] = 0;
				}
			}
			else {
				$req = "DELETE FROM `participant` WHERE `participant`.`evt_id` = '" . $args['eventId'] . "' AND `participant`.`uti_id` = '" . $args['userId'] . "';";
				$res = mysql_query($req);
				if($res) {
					$return["back"] = 0;
				}
			}
		}
	}
	mysql_close();

	return $return;
}

function createEvent($args) {
	$return = array("back" => 1);

	$req  = "INSERT INTO `evenement` (`evt_id`, `evt_debut`, `evt_fin`, `evt_latitude`, `evt_longitude`,  `spr_id`, `evt_prive`, `evt_nombreParticipant`) ";
	$req .= "VALUES (NULL, ";
	$req .= "'" . $args['evt_debut'] . "', '";
	$req .= $args['evt_fin'] . "', '";
	$req .= $args['evt_latitude'] . "', '";
	$req .= $args['evt_longitude'] . "', '";
	$req .= $args['spr_id'] . "', '";
	$req .= $args['evt_prive'] . "', '";
	$req .= $args['evt_nombreParticipant'] . "');";

	mysql_init();
	$res = mysql_query($req);
	if($res)
	{
		$req2  = "SELECT `evt_id` ";
		$req2 .= "FROM `evenement` ";
		$req2 .= "WHERE `evt_debut` = '" . $args['evt_debut'] . "' ";
		$req2 .= "AND `evt_fin` = '" . $args['evt_fin'] . "' ";
		$req2 .= "AND `evt_latitude` = '" . $args['evt_latitude'] . "' ";
		$req2 .= "AND `evt_longitude` = '" . $args['evt_longitude'] . "' ";
		$req2 .= "AND `spr_id` = '" . $args['spr_id'] . "' ";
		$req2 .= "AND `evt_prive` = '" . $args['evt_prive'] . "' ";
		$req2 .= "AND `evt_nombreParticipant` = '" . $args['evt_nombreParticipant'] . "'";
		$req2 .= ";";
		$res2 = mysql_query($req2);
		if($row2 = mysql_fetch_row($res2))
		{
			$req3  = "INSERT INTO  `participant` (`evt_id`, `uti_id`, `prt_createur`) ";
			$req3 .= "VALUES ('" . $row2[0] . "', '" . $args['uti_id'] . "', '1');";
			$res3 = mysql_query($req3);
			if($res3)
			{
				$req4  = "INSERT INTO  `commentaire` (`evt_id`, `com_id`, `uti_id`, `com_contenu`, `com_date`) ";
				$req4 .= "VALUES ('" . $row2[0] . "', '0', '" . $args['uti_id'] . "', '" . nl2br(htmlentities($args['com_contenu'])) . "', NOW());";
				$res4 = mysql_query($req4);
				if($res4)
				{
					$return["back"] = 0;
				}
			}
		}
	}
	mysql_close();

	return $return;
}

function loadFriendList($args) {
	$return = array(
			"back" => 1,
			"list" => array()
	);
	
	$req  = "SELECT `utilisateur`.`uti_id`, `uti_email`, `uti_nom`, `uti_prenom`, `uti_naissance`, `uti_ville` FROM `utilisateur`";
	$req .=	" JOIN `contact` ON `utilisateur`.`uti_id` = `contact`.`uti_id2` ";
	$req .= " WHERE `contact`.`uti_id1` = " . $args['userId'] . ";";

	mysql_init();
	$res = mysql_query($req);
	if($res) {
		$return["back"] = 0;
		while($row = mysql_fetch_assoc($res)) {
			array_push($return["list"], $row);
		}
	}
	mysql_close();
	
	return $return;
}

function addFriend($args) {
	$return = array(
			"back" => 1
	);
	
	$req  = "INSERT INTO `sportincp_dev`.`contact` (`uti_id1`, `uti_id2`) ";
	$req .= "VALUES";
	$sep = "";
	foreach ($args['friendId'] as $fid) {
		$req .= $sep . " (" . $args['userId'] . ", " . $fid . ")";
		if ($sep == "") {
			$sep = ",";
		}
	}
	$req .= ";";

	mysql_init();
	$res = mysql_query($req);
	if($res)
	{
		$return["back"] = 0;
	}
	mysql_close();

	return $return;
}

function addFriendName($args) {
	$return = array(
			"back" => 1
	);
	
	$arrUserId = array();
	
	// Recupération des ID
	$req  = "SELECT `uti_id` FROM `utilisateur` WHERE CONCAT(`uti_prenom`, ' ', `uti_nom`)";
	if(count($args['friendName']) == 1) {
		$req .= " = '" . $args['friendName'][0] . "'";
	}
	else {
		$req .= " IN (";
		$sep = "";
		foreach ($args['friendName'] as $fname) {
			$req .= $sep . "'" . $fname . "'";
			if ($sep == "") {
				$sep = ", ";
			}
		}
		$req .= ")";
	}
	$req .= ";";
	
	mysql_init();
	$res = mysql_query($req);
	if($res)
	{
		while($row = mysql_fetch_assoc($res)) {
			array_push($arrUserId, $row["uti_id"]);
		}
	}
	else {
		mysql_close();
		return $return;
	}
	
	// Controle de la liste des ID
	if(count($arrUserId) == 0) {
		$return["back"] = 2;
		mysql_close();
		return $return;
	}
	
	// Ajout des amis
	$req2  = "INSERT INTO `sportincp_dev`.`contact` (`uti_id1`, `uti_id2`) ";
	$req2 .= "VALUES";
	$sep = "";
	foreach ($arrUserId as $fid) {
		$req2 .= $sep . " (" . $args['userId'] . ", " . $fid . ")";
		if ($sep == "") {
			$sep = ",";
		}
	}
	$req2 .= ";";
	$res2 = mysql_query($req2);
	if($res2)
	{
		$return["back"] = 0;
	}
	mysql_close();

	return $return;
}

function delFriend($args) {
	$return = array(
			"back" => 1
	);
	
	$req  = "DELETE FROM `sportincp_dev`.`contact` WHERE `contact`.`uti_id1` = 15 AND `contact`.`uti_id2` ";
	if(count($args['friendId']) == 1) {
		$req .= " = " . $args['friendId'][0];
	}
	else {
		$req .= " IN (";
		$sep = "";
		foreach ($args['friendId'] as $fid) {
			$req .= $sep . $fid;
			if ($sep == "") {
				$sep = ", ";
			}
		}
		$req .= ")";
	}
	$req .= ";";

	mysql_init();
	$res = mysql_query($req);
	if($res)
	{
		$return["back"] = 0;
	}
	mysql_close();

	return $return;
}


function autoCompleteUserName($args) {
	$return = array(
			"back" => 1,
			"list" => array()
	);
	
	if(!isset($args['friendName'])) {
		$return["back"] = 2;
		return $return;
	}
	
	if(strlen($args['friendName']) < 4) {
		$return["back"] = 0;
		return $return;
	}
	
	$req  = "SELECT CONCAT(`uti_prenom`, ' ', `uti_nom`) ";
	$req .= "FROM `utilisateur` ";
	$req .= "WHERE UPPER(CONCAT(`uti_prenom` ,  ' ',  `uti_nom`)) LIKE UPPER('%" . $args['friendName'] . "%') ";
	$req .= "ORDER BY CONCAT(`uti_prenom`, ' ', `uti_nom` ) ";
	$req .= "LIMIT 5;";

	mysql_init();
	$res = mysql_query($req);
	if($res)
	{
		$return["back"] = 0;
		while($row = mysql_fetch_array($res)) {
			array_push($return["list"], $row[0]);
		}
	}
	mysql_close();

	return $return;
}

function inviteForEvent($args) {	
	$return = array(
			"back" => 1
	);
	
	$req  = "INSERT INTO `participant`(`evt_id`, `uti_id`, `prt_createur`, `prt_acc`) ";
	$req .= "VALUES";
	$sep = "";
	foreach ($args['friendId'] as $fid) {
		$req .= $sep . " (" . $args['eventId'] . ", " . $fid . ", 0, 0)";
		if ($sep == "") {
			$sep = ",";
		}
	}
	$req .= ";";

	mysql_init();
	$res = mysql_query($req);
	if($res)
	{
		$return["back"] = 0;
	}
	mysql_close();

	return $return;
}

function loadEventCom($args) {
	$return = array(
			"back" => 1,
			"list" => array()
	);
	
	$req  = "SELECT `com_id`, `com_date`, `com_contenu` , CONCAT(`uti_prenom` , ' ',  `uti_nom`) as `uti_nom` ";
	$req .= "FROM `commentaire` ";
	$req .= "JOIN `utilisateur` ON `utilisateur`.`uti_id` = `commentaire`.`uti_id` ";
	$req .= "WHERE `com_id` != 0 ";
	$req .= "AND `commentaire`.`evt_id` = " . $args["eventId"] . ";";

	mysql_init();
	$res = mysql_query($req);
	if($res)
	{
		$return["back"] = 0;
		while($row = mysql_fetch_array($res)) {
			array_push($return["list"], $row);
		}
	}
	mysql_close();

	return $return;
}

function addNewComment($args) {	
	$return = array(
			"back" => 1
	);

	// Recupération l'ID
	$req  = "SELECT MAX(`com_id`) FROM `commentaire` WHERE `evt_id` = " . $args['eventId'] . ";";
	mysql_init();
	$res = mysql_query($req);
	if($res)
	{
		while($row = mysql_fetch_array($res)) {
			$comId = $row[0] + 1;
		}
	}
	else {
		mysql_close();
		return $return;
	}
	
	$req2  = "INSERT INTO  `commentaire` (`evt_id`, `com_id`, `uti_id`, `com_contenu`, `com_date`) ";
	$req2 .= "VALUES ('" . $args['eventId'] . "', " . $comId . ", '" . $args['userId'] . "', '" . nl2br(htmlentities($args['comment'])) . "', NOW());";
	$res2 = mysql_query($req2);
	if($res2)
	{
		$return["back"] = 0;
	}
	mysql_close();

	return $return;
}

function inviteResponse($args) {
	if(!isset($args['eventId']) || !isset($args['userId'])) {
		return array("back" => 2);
	}
	if(empty($args['eventId']) || empty($args['userId'])) {
		return array("back" => 3);
	}
	$return = array("back" => 1);

	if($args["response"] == 0) {
		return subscription($args);
	}
	
	mysql_init();
	$req = "UPDATE `participant` SET `prt_acc` =  '1' WHERE `participant`.`evt_id` = " . $args['eventId'] . " AND `participant`.`uti_id` = " . $args['userId'] . ";";
	$res = mysql_query($req);
	if($res) {
		$return["back"] = 0;
	}
	mysql_close();

	return $return;
}

function getInvitations($args) {
	if(!isset($args['userId'])) {
		return array("back" => 2);
	}
	if(empty($args['userId'])) {
		return array("back" => 3);
	}
	$return = array("back" => 1,
			"nbInvitation" => 0,
			"event" => array()
	);
	
	$selectReq  = "SELECT `evenement`.`evt_id` ,  `evt_debut` ,  `evt_fin` ,  `evt_latitude` ,  `evt_longitude` ,  `evt_nombreParticipant` ,  `sport`.`spr_id` ,  `spr_libelle`, `owner`.`uti_id`, `evt_prive`, `commentaire`.`com_contenu`, COALESCE(`invite`.`prt_acc`,-1) as `invite`";
	$countReq  =  "SELECT COUNT(`evenement`.`evt_id`) as nbNotification";
	$condReq  =   " FROM  `evenement`";
	$condReq .=   " JOIN `sport` ON  `sport`.`spr_id` =  `evenement`.`spr_id`";
	$condReq .=   " JOIN `commentaire` ON  `commentaire`.`evt_id` =  `evenement`.`evt_id` AND `commentaire`.`com_id` = 0";
	$condReq .=   " JOIN `participant` AS `owner` ON `evenement`.`evt_id` = `owner`.`evt_id` AND `owner`.`prt_createur` = 1";
	$condReq .=   " JOIN `participant` AS `invite` ON `evenement`.`evt_id` = `invite`.`evt_id` AND `invite`.`prt_acc` = 0 AND `invite`.`uti_id` = " . $args['userId'];
	$limitReq .=  " LIMIT 1";
	
	mysql_init();
	$req = $countReq . $condReq . ";";
	$res = mysql_query($req);
	if(!$res) {
		mysql_close();
		return $return;
	}
	
	if($row = mysql_fetch_array($res)) {
		$return["nbInvitation"] = $row[0];
	}
	
	if($return["nbInvitation"] > 1) {
		$return["back"] = 0;
		mysql_close();
		return $return;
	}

	$req2 = $selectReq . $condReq . $limitReq . ";";
	$res2 = mysql_query($req2);
	if($res2) {
		$return["back"] = 0;
		if($row2 = mysql_fetch_array($res2)) {
			array_push($return["event"], $row2);
		}
	}
	
	mysql_close();
	
	return $return;
}

function loadParticipationList($args)
{
	$return = array(
			"back" => 1,
			"list" => array()
	);
	
	$req  = "SELECT `evenement`.`evt_id` ,  `evt_debut` ,  `evt_fin` ,  `evt_latitude` ,  `evt_longitude` ,  `evt_nombreParticipant` ,  `sport`.`spr_id` ,  `spr_libelle`, `owner`.`uti_id`, `evt_prive`, `commentaire`.`com_contenu`, COALESCE(`invite`.`prt_acc`,-1) as `invite` FROM  `evenement`";
	$req .=	" JOIN `sport` ON  `sport`.`spr_id` =  `evenement`.`spr_id`";
	$req .=	" JOIN `commentaire` ON  `commentaire`.`evt_id` =  `evenement`.`evt_id` AND `commentaire`.`com_id` = 0";
	$req .= " JOIN `participant` AS `owner` ON `evenement`.`evt_id` = `owner`.`evt_id` AND `owner`.`prt_createur` = 1";
	$req .= " JOIN `participant` AS `invite` ON `evenement`.`evt_id` = `invite`.`evt_id` AND `invite`.`uti_id` = " . $args['userId'] . " AND `invite`.`prt_acc` = 1";
	$req .= " WHERE `evenement`.`evt_fin` > NOW()";
	$req .=	" ORDER BY `evt_debut` LIMIT 20;";
	//echo $req;

	mysql_init();
	$res = mysql_query($req);
	if($res) {
		$return["back"] = 0;
		while($row = mysql_fetch_assoc($res)) {
			array_push($return["list"], $row);
		}
	}
	mysql_close();

	return $return;
}

function getSponsorsPosition($args)
{
	$return = array(
			"back" => 1,
			"list" => array()
	);

	$req  = "SELECT `magasin`.`mag_latitude`, `magasin`.`mag_longitude`, `magasin`.`mag_libelle`, `magasin`.`mag_adr`, `magasin`.`mag_cp`, `magasin`.`mag_ville`, `enseigne`.`ens_type_cpt`";
	$req .=	" FROM `magasin`";
	$req .=	" JOIN `enseigne` ON `enseigne`.`ens_id` = `magasin`.`ens_id`";
	$req .=	" WHERE `magasin`.`mag_latitude` > " . $args['minLat'] . " AND `magasin`.`mag_latitude` < " . $args['maxLat'] . " AND `magasin`.`mag_longitude` > " . $args['minLong'] . " AND `magasin`.`mag_longitude` < " . $args['maxLong'] . ";";
	//echo $req;

	mysql_init();
	$res = mysql_query($req);
	if($res) {
		$return["back"] = 0;
		while($row = mysql_fetch_assoc($res)) {
			$row["zoom_lvl"] = 0;
			if($row["ens_type_cpt"] < 2 ) {
				$row["zoom_lvl"] = 18;
			}
			array_push($return["list"], $row);
		}
	}
	mysql_close();

	return $return;
}

function getAdsCycle($args)
{
	require_once("pub.php");
	
	$return = array(
			"back" => 1,
			"list" => array()
	);
	
	$bdd = mysql_pdo_init();
	if(!$bdd) {
		return $return;
	}
	
	$return["back"] = 0;
	$return["list"] = getPubCycle($bdd);

	return $return;
}

// TODO : A supprimer, pour test
function testCo() {
	$return = array(
			"back" => 0,
			"env"  => APPLICATION_ENV,
			"adr"  => Config::get("adr"),
			"db"   => Config::get("db"),
			"usr"  => Config::get("usr"),
			"psw"  => Config::get("psw")
	);

	return $return;
}